<template>
  <div class="data-source-edit p-4">
    <!-- 页面标题 -->
    <div class="page-header mb-5">
      <h2 class="text-2xl font-bold mb-1 flex items-center">
        <div class="i-carbon-data-base text-primary mr-2 text-3xl"></div>
        {{ isEdit ? (isView ? '查看数据源' : '编辑数据源') : '注册数据源' }}
      </h2>
      <p class="text-gray-500 text-sm">{{ isEdit ? '修改已有数据源信息' : '添加新的数据源到数据中台系统' }}</p>
    </div>

    <!-- 操作区 -->
    <div class="flex justify-between mb-4">
      <div>
        <el-button @click="goBack" class="flex items-center">
          <div class="i-carbon-arrow-left mr-1"></div>返回列表
        </el-button>
      </div>
      <div v-if="isView">
        <el-button type="primary" @click="switchToEdit" class="flex items-center">
          <div class="i-carbon-edit mr-1"></div>编辑
        </el-button>
      </div>
    </div>

    <!-- 表单区 -->
    <el-card class="border-0 shadow-sm">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        :disabled="isView"
      >
        <!-- 基本信息 -->
        <div class="form-section mb-6">
          <div class="section-header flex items-center mb-4 border-b pb-2">
            <div class="i-carbon-information text-primary mr-2"></div>
            <span class="text-lg font-medium">基本信息</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择数据库类型" style="width: 100%">
                  <el-option v-for="item in dbTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input 
                  v-model="form.description" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入数据源描述信息" 
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 连接信息 -->
        <div class="form-section mb-6">
          <div class="section-header flex items-center mb-4 border-b pb-2">
            <div class="i-carbon-connection text-primary mr-2"></div>
            <span class="text-lg font-medium">连接信息</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="连接URL" prop="url">
                <el-input v-model="form.url" placeholder="请输入连接URL">
                  <template #prepend>
                    <div :class="getDbTypeIcon(form.type)" class="mr-1"></div>
                    <span>{{ getJdbcPrefix(form.type) }}</span>
                  </template>
                </el-input>
                <div class="mt-1 text-xs text-gray-500">
                  {{ getJdbcFormatHint(form.type) }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入连接用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" placeholder="请输入连接密码" show-password />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item v-if="needsSchema" label="模式名/数据库" prop="schemaName">
                <el-input v-model="form.schemaName" placeholder="请输入模式名/数据库名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.type === 'Oracle'" label="对象所有者" prop="owner">
                <el-input v-model="form.owner" placeholder="请输入数据库对象所有者" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" v-if="needsDriverClass">
            <el-col :span="24">
              <el-form-item label="驱动类" prop="driverClass">
                <el-input v-model="form.driverClass" placeholder="请输入数据库驱动类" />
                <div class="mt-1 text-xs text-gray-500">
                  {{ getDriverClassHint(form.type) }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 其他设置 -->
        <div class="form-section mb-6">
          <div class="section-header flex items-center mb-4 border-b pb-2">
            <div class="i-carbon-settings text-primary mr-2"></div>
            <span class="text-lg font-medium">其他设置</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态">
                <el-switch
                  v-model="form.status"
                  :active-value="'1'"
                  :inactive-value="'0'"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 表单操作 -->
        <div class="form-actions mt-6 flex justify-center">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleTestConnection" :loading="testLoading" class="flex items-center" v-if="!isView">
            <div class="i-carbon-settings-check mr-1"></div>测试连接
          </el-button>
          <el-button type="success" @click="handleSubmit" :loading="submitLoading" class="flex items-center" v-if="!isView">
            <div class="i-carbon-checkmark mr-1"></div>{{ isEdit ? '保存' : '提交' }}
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 测试连接结果对话框 -->
    <el-dialog v-model="testDialogVisible" title="连接测试结果" width="500px">
      <div v-if="testLoading" class="flex flex-col items-center">
        <el-icon class="is-loading mb-4 text-3xl"><Loading /></el-icon>
        <span>正在测试连接，请稍候...</span>
      </div>
      <div v-else-if="testSuccess" class="flex flex-col items-center">
        <div class="i-carbon-checkmark-filled text-green-500 text-5xl mb-4"></div>
        <div class="text-lg font-medium">连接成功</div>
        <div class="text-gray-500 mt-2">数据源连接测试通过，可以正常使用</div>
      </div>
      <div v-else class="flex flex-col items-center">
        <div class="i-carbon-error-filled text-red-500 text-5xl mb-4"></div>
        <div class="text-lg font-medium">连接失败</div>
        <div class="text-gray-500 mt-2">{{ testErrorMessage }}</div>
      </div>
      <template #footer>
        <el-button @click="testDialogVisible = false">关闭</el-button>
        <el-button v-if="!testSuccess" type="primary" @click="handleTestConnection">重试</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 组件状态
const isView = computed(() => route.query.mode === 'view')
const isEdit = computed(() => !!route.query.id)
const dataSourceId = computed(() => route.query.id as string)

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 数据库类型选项
const dbTypeOptions = [
  { label: 'MySQL', value: 'MySQL' },
  { label: 'Oracle', value: 'Oracle' },
  { label: 'SQL Server', value: 'SQLServer' },
  { label: 'PostgreSQL', value: 'PostgreSQL' },
  { label: 'MongoDB', value: 'MongoDB' },
  { label: 'Redis', value: 'Redis' },
  { label: 'Hive', value: 'Hive' },
  { label: 'HBase', value: 'HBase' },
]

// 表单数据
const defaultForm = {
  id: '',
  name: '',
  type: 'MySQL',
  url: '',
  driverClass: '',
  username: '',
  password: '',
  schemaName: '',
  owner: '',
  description: '',
  status: '1',
  createTime: '',
  createUser: '',
  updateTime: '',
  updateUser: '',
}

const form = reactive({ ...defaultForm })

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入数据源名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  url: [
    { required: true, message: '请输入连接URL', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入连接用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入连接密码', trigger: 'blur' }
  ],
  schemaName: [
    { required: false, message: '请输入模式名/数据库名', trigger: 'blur' }
  ],
  driverClass: [
    { required: false, message: '请输入数据库驱动类', trigger: 'blur' }
  ]
})

// 测试连接相关
const testDialogVisible = ref(false)
const testLoading = ref(false)
const testSuccess = ref(false)
const testErrorMessage = ref('')

// 计算属性
const needsSchema = computed(() => ['MySQL', 'Oracle', 'PostgreSQL', 'SQLServer', 'MongoDB', 'Hive'].includes(form.type))
const needsDriverClass = computed(() => ['Oracle', 'SQLServer', 'Hive'].includes(form.type))

// 根据数据库类型获取图标
const getDbTypeIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'MySQL': 'i-logos-mysql',
    'Oracle': 'i-logos-oracle',
    'SQLServer': 'i-logos-microsoft',
    'PostgreSQL': 'i-logos-postgresql',
    'MongoDB': 'i-logos-mongodb',
    'Redis': 'i-logos-redis',
    'Hive': 'i-logos-hadoop',
    'HBase': 'i-logos-hbase',
  }
  return iconMap[type] || 'i-carbon-data-base'
}

// 根据数据库类型获取JDBC前缀
const getJdbcPrefix = (type: string) => {
  const prefixMap: Record<string, string> = {
    'MySQL': 'jdbc:mysql://',
    'Oracle': 'jdbc:oracle:thin:@',
    'SQLServer': 'jdbc:sqlserver://',
    'PostgreSQL': 'jdbc:postgresql://',
    'MongoDB': 'mongodb://',
    'Redis': 'redis://',
    'Hive': 'jdbc:hive2://',
    'HBase': '',
  }
  return prefixMap[type] || ''
}

// 根据数据库类型获取JDBC格式提示
const getJdbcFormatHint = (type: string) => {
  const hintMap: Record<string, string> = {
    'MySQL': '示例: server-host:3306/database_name',
    'Oracle': '示例: server-host:1521:SID',
    'SQLServer': '示例: server-host:1433;databaseName=database_name',
    'PostgreSQL': '示例: server-host:5432/database_name',
    'MongoDB': '示例: server-host:27017/database_name',
    'Redis': '示例: server-host:6379/0',
    'Hive': '示例: server-host:10000/default',
    'HBase': '示例: server-host:2181',
  }
  return hintMap[type] || '请输入正确的连接URL格式'
}

// 根据数据库类型获取驱动类提示
const getDriverClassHint = (type: string) => {
  const hintMap: Record<string, string> = {
    'Oracle': '示例: oracle.jdbc.driver.OracleDriver',
    'SQLServer': '示例: com.microsoft.sqlserver.jdbc.SQLServerDriver',
    'Hive': '示例: org.apache.hive.jdbc.HiveDriver',
  }
  return hintMap[type] || ''
}

// 获取数据源详情
const getDataSourceDetail = (id: string) => {
  if (!id) return

  // 模拟接口调用
  setTimeout(() => {
    // 模拟数据
    const mockData = {
      id: id,
      name: `示例数据源${id.split('_')[1] || ''}`,
      type: dbTypeOptions[parseInt(id.split('_')[1] || '1') % dbTypeOptions.length].value,
      url: `server-${id.split('_')[1] || '1'}.example.com:3306/db_${id.split('_')[1] || '1'}`,
      driverClass: 'com.mysql.cj.jdbc.Driver',
      username: `user_${id.split('_')[1] || '1'}`,
      password: '********',
      schemaName: `db_${id.split('_')[1] || '1'}`,
      owner: `owner_${parseInt(id.split('_')[1] || '1') % 3}`,
      description: `这是一个示例数据源，ID为${id}`,
      status: parseInt(id.split('_')[1] || '1') % 5 === 0 ? '0' : '1',
      createTime: new Date(Date.now() - 10000000000).toLocaleString(),
      createUser: 'admin',
      updateTime: new Date(Date.now() - 5000000000).toLocaleString(),
      updateUser: 'admin',
    }

    // 更新表单
    Object.keys(mockData).forEach(key => {
      form[key as keyof typeof form] = mockData[key as keyof typeof mockData]
    })
  }, 500)
}

// 返回列表页
const goBack = () => {
  router.push({ path: '/metadata/DataSourceList' })
}

// 切换到编辑模式
const switchToEdit = () => {
  router.replace({ path: '/metadata/DataSourceEdit', query: { id: dataSourceId.value, mode: 'edit' } })
}

// 测试连接
const handleTestConnection = () => {
  // 先验证表单
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('请完善表单信息后再测试连接')
      return
    }

    testDialogVisible.value = true
    testLoading.value = true
    testSuccess.value = false
    testErrorMessage.value = ''
    
    // 模拟接口调用
    setTimeout(() => {
      testLoading.value = false
      
      // 随机测试结果，实际应该调用接口
      if (Math.random() > 0.3) {
        testSuccess.value = true
      } else {
        testSuccess.value = false
        const errors = [
          '连接超时，请检查网络或地址是否正确',
          '认证失败，请检查用户名和密码',
          '数据库不存在，请检查配置',
          '权限不足，无法建立连接',
          '驱动程序未找到，请检查配置'
        ]
        testErrorMessage.value = errors[Math.floor(Math.random() * errors.length)]
      }
    }, 1500)
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    
    submitLoading.value = true
    
    // 模拟接口调用
    setTimeout(() => {
      submitLoading.value = false
      
      ElMessage({
        type: 'success',
        message: isEdit.value ? '数据源更新成功' : '数据源创建成功'
      })
      
      goBack()
    }, 1000)
  })
}

// 初始化
onMounted(() => {
  if (isEdit.value) {
    getDataSourceDetail(dataSourceId.value)
  }
})
</script>

<style scoped>
.form-section {
  position: relative;
}
</style> 